# -*- coding: utf-8 -*- 
# @File : test2.py
# @Time : 2019/10/26 20:26 
# @Author : yaozi
# @Contact : xt1512326654@sina.cn
from myarray2d import Array2D
from priorityqueue import PriorityQueue
from puzzle8 import Puzzle8, randint


def pz():
    a = Array2D(3, 3)
    a[0, 0] = 0
    a[0, 1] = 1
    a[0, 2] = 2

    a[1, 0] = 3
    a[1, 1] = 4
    a[1, 2] = 5

    a[2, 0] = 6
    a[2, 1] = 7
    a[2, 2] = 8

    b = {}

    for rows in range(a.numRows()):
        for cols in range(a.numCols()):
            b[(rows, cols)] = a[rows, cols]
            print(a[rows, cols], end=" ")
            if (cols + 1) % a.numCols() == 0:
                print("\n", end="")
    print("\n", end="")
    dd = getTheNeighbor((0, 1))
    puzzle8 = Puzzle8()
    came_fram = {}
    ss(puzzle8, came_fram)
    came_fram


def ss(puzzle8, came_fram):
    frontier = PriorityQueue()
    cost_so_for = {}
    frontier.enqueue(puzzle8, 0)
    cost_so_for[puzzle8] = puzzle8.cost
    came_fram[puzzle8] = None
    while not frontier.is_empty():
        puzzle8 = frontier.dequeue()
        print(puzzle8.num)
        if puzzle8.isGoal():
            return puzzle8
        else:
            for newp in puzzle8.getAllMoves():
                new = puzzle8.clone()
                new.move(newp[0], newp[1])
                new_cost = new.cost
                print(new.num)
                if new not in cost_so_for or new_cost < cost_so_for[new]:
                    cost_so_for[new] = new_cost
                    property = new_cost + new.heuristics
                    frontier.enqueue(new, property)
                    came_fram[new] = puzzle8
    return None


# 获取相邻元组
def getTheNeighbor(tuple):
    row = tuple[0]
    col = tuple[1]
    moves = []
    offsets = [(0, -1), (-1, 0), (1, 0), (0, 1)]
    for x, y in offsets:
        x = row + x
        y = col + y
        if 0 <= x < 3 and 0 <= y < 3:
            moves.append((x, y))
    return moves


if __name__ == '__main__':
    pz()
